/**
 *@Title: IncomingServiceImpl.java  
 * @author: 胡彪
 * @date: 2013-6-1 下午03:12:58
 * @Description:
 * @version: V1.0   
 */
package com.imonsoft.sqm.service.business.ipic_system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import com.google.gson.reflect.TypeToken;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.dao.business.ipic_system.IncomingDAO;
import com.imonsoft.sqm.pojo.basedata.Part;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.ipic_system.Incoming;
import com.imonsoft.sqm.pojo.business.ipic_system.IncomingExample;
import com.imonsoft.sqm.service.basedata.PartService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.validator.basedata.IncomingValidator;
import com.imonsoft.sqm.vo.business.ipic_system.IncomingVo;
import com.imonsoft.sqm.web.excel.IncomingExcel.IncomingImportDto;

/**
 *
 *
 */
@Service("incomingService")
public class IncomingServiceImpl implements IncomingService {

	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	private IncomingDAO incomingDAO;

	@Autowired
	private SupplierService supplierService;

	@Autowired
	private PartService partService;

	@Autowired
	private IncomingValidator incomingValidator;

	@Override
	public DataGrid<IncomingVo> getDataGridVoBy(Incoming incoming, Pager pager) {

		return incomingDAO.getDataGridVoBy(incoming, pager);
	}

	@Override
	public void txAddIncoming(String incoming, String incomingDetail, ReturnMessage message, BindingResult result) throws Exception {

		Incoming vo = new Incoming();
		List<Incoming> incomingList = new ArrayList<Incoming>();
		Map<String, String> map = null;
		List<Map<String, String>> list = null;
		if (StringUtil.isNotBlank(incoming)) {
			map = JsonUtil.json2Bean(incoming, new TypeToken<Map<String, String>>() {
			});
		}
		if (StringUtil.isNotBlank(incomingDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(incomingDetail, new TypeToken<List<Map<String, String>>>() {
			});
		}
		if (map != null) {
			String date = map.get("year");
			BeanUtils.populate(vo, map);
			vo.setYear(date);
		}
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				Incoming bean = new Incoming();
				BeanUtils.populate(bean, detailMap);
				incomingList.add(bean);
			}
		}

		Supplier supplier = supplierService.get(vo.getSupplierId());
		Part part = partService.get(vo.getPartId());
		vo.setSupplierCode(supplier.getCode());
		vo.setSupplierName(supplier.getName());
		vo.setPartCode(part.getCode());
		vo.setPartName(part.getName());
		incomingValidator.methodAddValidate(vo, result);

		if (result.hasErrors()) {
			message.setObj(incomingValidator.getErrors(result));
		} else {
			
			List<Incoming> bean = findListByState(vo);
			if (bean != null && bean.size() > 0) {
				for (Incoming incoming2 : bean) {
					incoming2.setAmount(null);
					incoming2.setComment(null);
					incoming2.setState(ConstantSqm.STATUS_NORMAL);
					incomingDAO.updateIncomingByPrimaryKey(incoming2);
				}
			} 
			
			
			for (Incoming incoming2 : incomingList) {

				incoming2.setPartId(vo.getPartId());
				incoming2.setSupplierId(vo.getSupplierId());
				incoming2.setSupplierCode(supplier.getCode());
				incoming2.setSupplierName(supplier.getName());
				incoming2.setPartCode(part.getCode());
				incoming2.setPartName(part.getName());
				incoming2.setYear(vo.getYear());
				incoming2.setState(ConstantSqm.STATUS_NORMAL);
				
				if (incoming2.getAmount() != null || !StringUtil.isBlank( incoming2.getComment())) {
					List<Incoming> objList=findListByStatusNormal(incoming2);
					if (objList != null && objList.size() > 0) {
						Incoming obj = objList.get(0);
						obj.setAmount(incoming2.getAmount());
						obj.setComment(obj.getComment());
						incomingDAO.updateIncomingByPrimaryKey(obj);
					} else {
						incomingDAO.insertIncomingSelective(incoming2);
					}
				}
			}
			message.setSuccess(true);
			message.setMsg(ConstantSqm.OPERATE_SUCCESS);
		}
	}

	@Override
	public IncomingVo getModifyData(Long sid, Long pid, String year) {
		IncomingVo vo = new IncomingVo();

		for (int i = 1; i <= 12; i++) {
			Incoming bean = null;
			IncomingExample example = new IncomingExample();
			IncomingExample.Criteria criteria = example.createCriteria();
			criteria.andPartIdEqualTo(pid);
			criteria.andSupplierIdEqualTo(sid);
			criteria.andYearEqualTo(year);
			criteria.andMonthEqualTo(StringUtil.paddingZero(String.valueOf(i),2));
			List<Incoming> list = incomingDAO.selectIncomingByExample(example);
			if (list != null && list.size() != 0) {
				bean = list.get(0);
				vo.setSid(StringUtil.fixup(bean.getSupplierId()));
				vo.setSupplierName(bean.getSupplierName());
				vo.setSupplierCode(bean.getSupplierCode());
				vo.setPid(StringUtil.fixup(bean.getPartId()));
				vo.setPartName(bean.getPartName());
				vo.setYear(bean.getYear());
				vo.setPartNum(bean.getPartCode());
				if (i == 1) {
					vo.setJanuary(StringUtil.fixup(bean.getAmount()));
					vo.setJanuaryComment(bean.getComment());

				} else if (i == 2) {
					vo.setFebruary(StringUtil.fixup(bean.getAmount()));
					vo.setFebruaryComment(bean.getComment());

				} else if (i == 3) {
					vo.setMarch(StringUtil.fixup(bean.getAmount()));
					vo.setMarchComment(bean.getComment());

				} else if (i == 4) {

					vo.setApril(StringUtil.fixup(bean.getAmount()));
					vo.setAprilComment(bean.getComment());
				} else if (i == 5) {
					vo.setMay(StringUtil.fixup(bean.getAmount()));
					vo.setMayComment(bean.getComment());

				} else if (i == 6) {
					vo.setJune(StringUtil.fixup(bean.getAmount()));
					vo.setJuneComment(bean.getComment());

				} else if (i == 7) {
					vo.setJuly(StringUtil.fixup(bean.getAmount()));
					vo.setJulyComment(bean.getComment());

				} else if (i == 8) {
					vo.setAugust(StringUtil.fixup(bean.getAmount()));
					vo.setAugustComment(bean.getComment());

				} else if (i == 9) {
					vo.setSeptember(StringUtil.fixup(bean.getAmount()));
					vo.setSeptemberComment(bean.getComment());

				} else if (i == 10) {
					vo.setOctober(StringUtil.fixup(bean.getAmount()));
					vo.setOctoberComment(bean.getComment());

				} else if (i == 11) {
					vo.setNovember(StringUtil.fixup(bean.getAmount()));
					vo.setNovemberComment(bean.getComment());

				} else if (i == 12) {
					vo.setDecember(StringUtil.fixup(bean.getAmount()));
					vo.setDecemberComment(bean.getComment());

				}

			}

		}

		return vo;
	}

	@Override
	public void txUpdateOrAddIncoming(String incoming, String incomingDetail) throws Exception {

		Incoming bean = null;
		Map<String, String> map = null;
		List<Map<String, String>> list = null;
		List<Incoming> incomingList = new ArrayList<Incoming>();
		if (StringUtil.isNotBlank(incoming)) {
			map = JsonUtil.json2Bean(incoming, new TypeToken<Map<String, String>>() {
			});
		}
		if (StringUtil.isNotBlank(incomingDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(incomingDetail, new TypeToken<List<Map<String, String>>>() {
			});
		}

		if (map != null) {
			bean = new Incoming();
			BeanUtils.populate(bean, map);
			bean.setYear(map.get("year"));
		}

		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				Incoming dto = new Incoming();
				BeanUtils.populate(dto, detailMap);
				incomingList.add(dto);
			}
		}

		Supplier supplier = supplierService.get(bean.getSupplierId());
		Part part = partService.get(bean.getPartId());

		for (int i = 1; i <= 12; i++) {
			Incoming incomingBean = null;

			IncomingExample example = new IncomingExample();
			IncomingExample.Criteria criteria = example.createCriteria();
			criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
			criteria.andYearEqualTo(bean.getYear());
			criteria.andSupplierIdEqualTo(bean.getSupplierId());
			criteria.andPartIdEqualTo(bean.getPartId());
			criteria.andMonthEqualTo(StringUtil.paddingZero(String.valueOf(i),2));

			List<Incoming> incomingbeanList = incomingDAO.selectIncomingByExample(example);
			// 修改
			if (incomingbeanList != null && incomingbeanList.size() != 0) {
				incomingBean = incomingbeanList.get(0);
				for (Incoming incoming2 : incomingList) {
					if (StringUtil.paddingZero(String.valueOf(i),2).equals(incoming2.getMonth())) {
						incomingBean.setAmount(incoming2.getAmount());
						incomingBean.setComment(incoming2.getComment());
						break;
					}
				}
				incomingDAO.updateIncomingByPrimaryKey(incomingBean);

			} else {

				for (int j = 0; j < incomingList.size(); j++) {
					Incoming obj = incomingList.get(j);
					if (StringUtil.paddingZero(String.valueOf(i),2).equals(obj.getMonth())) {
						// 新增
						Incoming coming = new Incoming();
						coming.setAmount(obj.getAmount());
						coming.setComment(obj.getComment());
						coming.setSupplierId(supplier.getId());
						coming.setSupplierCode(supplier.getCode());
						coming.setSupplierName(supplier.getName());
						coming.setPartId(part.getId());
						coming.setPartCode(part.getCode());
						coming.setPartName(part.getName());
						coming.setYear(bean.getYear());
						coming.setMonth(obj.getMonth());
						coming.setState(ConstantSqm.STATUS_NORMAL);
						if (!StringUtil.isBlank(coming.getComment()) || coming.getAmount() != null) {
							incomingDAO.insertIncoming(coming);
						}
						break;
					}

				}

			}

		}

	}

	@Override
	public void deleteIncoming(String incomingDetail) throws Exception {

		List<IncomingVo> incomingList = new ArrayList<IncomingVo>();
		List<Map<String, String>> list = null;
		if (StringUtil.isNotBlank(incomingDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(incomingDetail, new TypeToken<List<Map<String, String>>>() {
			});
		}
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				IncomingVo bean = new IncomingVo();
				BeanUtils.populate(bean, detailMap);
				incomingList.add(bean);
			}
		}
		if (incomingList.size() != 0) {
			for (IncomingVo incoming : incomingList) {

				IncomingExample example = new IncomingExample();
				IncomingExample.Criteria criteria = example.createCriteria();
				criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
				criteria.andYearEqualTo(incoming.getYear());
				criteria.andSupplierIdEqualTo(StringUtil.toLong(incoming.getSid()));
				criteria.andPartIdEqualTo(StringUtil.toLong(incoming.getPid()));

				List<Incoming> dataList = incomingDAO.selectIncomingByExample(example);
				if (dataList != null && dataList.size() != 0) {
					for (Incoming data : dataList) {
						data.setState(ConstantSqm.STATUS_DELETE);
						incomingDAO.updateIncomingByPrimaryKey(data);
					}
				}

			}
		}
	}
	@Override
	public int delete(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<Incoming> findList(Incoming entity) {

		IncomingExample example = new IncomingExample();
		IncomingExample.Criteria criteria = example.createCriteria();
		criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andYearEqualTo(entity.getYear());
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andPartIdEqualTo(entity.getPartId());

		return incomingDAO.selectIncomingByExample(example);

	}

	public List<Incoming> findListByState(Incoming entity) {

		IncomingExample example = new IncomingExample();
		IncomingExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andYearEqualTo(entity.getYear());
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andPartIdEqualTo(entity.getPartId());
		return incomingDAO.selectIncomingByExample(example);

	}
	
	public List<Incoming> findListByMonth(Incoming entity) {

		IncomingExample example = new IncomingExample();
		IncomingExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andYearEqualTo(entity.getYear());
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andPartIdEqualTo(entity.getPartId());
		criteria.andMonthEqualTo(entity.getMonth());
		return incomingDAO.selectIncomingByExample(example);

	}
	
	public List<Incoming> findListByStatusNormal(Incoming entity) {

		IncomingExample example = new IncomingExample();
		IncomingExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_NORMAL);
		criteria.andYearEqualTo(entity.getYear());
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andPartIdEqualTo(entity.getPartId());
		criteria.andMonthEqualTo(entity.getMonth());
		return incomingDAO.selectIncomingByExample(example);

	}

	@Override
	public Incoming get(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public DataGrid<Incoming> getDataGrid(Incoming entity, Pager pager) {
		// TODO Auto-generated method stub
		return null;
	}

	 

	@Override
	public int update(Incoming entity) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Long insert(Incoming entity) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * zhouwei 系统导入保存
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void txInsertForSys(List<IncomingImportDto> incomingImportDtoList){
		if (null == incomingImportDtoList) {
			throw new SystemException("提交数据不能为空");
		}
		for (IncomingImportDto s:incomingImportDtoList) {
			if(s.getCountJanuary()!=null&&StringUtil.isNotBlank(s.getCountJanuary())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountJanuary())));
				txAddOrUpdateForSys(1,s);
			}
			if(s.getCountFebruary()!=null&&StringUtil.isNotBlank(s.getCountFebruary())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountFebruary())));
				txAddOrUpdateForSys(2,s);
			}
			if(s.getCountMarch()!=null&&StringUtil.isNotBlank(s.getCountMarch())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountMarch())));
				txAddOrUpdateForSys(3,s);
			}
			if(s.getCountApril()!=null&&StringUtil.isNotBlank(s.getCountApril())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountApril())));
				txAddOrUpdateForSys(4,s);
			}
			if(s.getCountMay()!=null&&StringUtil.isNotBlank(s.getCountMay())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountMay())));
				txAddOrUpdateForSys(5,s);
			}
			if(s.getCountJune()!=null&&StringUtil.isNotBlank(s.getCountJune())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountJune())));
				txAddOrUpdateForSys(6,s);
			}
			if(s.getCountJuly()!=null&&StringUtil.isNotBlank(s.getCountJuly())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountJuly())));
				txAddOrUpdateForSys(7,s);
			}
			if(s.getCountAugust()!=null&&StringUtil.isNotBlank(s.getCountAugust())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountAugust())));
				txAddOrUpdateForSys(8,s);
			}
			if(s.getCountSeptember()!=null&&StringUtil.isNotBlank(s.getCountSeptember())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountSeptember())));
				txAddOrUpdateForSys(9,s);
			}
			if(s.getCountOctober()!=null&&StringUtil.isNotBlank(s.getCountOctober())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountOctober())));
				txAddOrUpdateForSys(10,s);
			}
			if(s.getCountNovember()!=null&&StringUtil.isNotBlank(s.getCountNovember())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountNovember())));
				txAddOrUpdateForSys(11,s);
			}
			if(s.getCountDecember()!=null&&StringUtil.isNotBlank(s.getCountDecember())){
				s.setAmount(Integer.parseInt(StringUtil.fixup(s.getCountDecember())));
				txAddOrUpdateForSys(12,s);
			}
		}
	}
	/**
	 * 新增或者修改，系統导入
	 * @param month
	 * @param incomingImportDto
	 */
	public void txAddOrUpdateForSys(int month,IncomingImportDto incomingImportDto){
		Incoming incomingBean = null;
		IncomingExample example = new IncomingExample();
		IncomingExample.Criteria criteria = example.createCriteria();
		criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andYearEqualTo(incomingImportDto.getYearStr());
		criteria.andSupplierIdEqualTo(incomingImportDto.getSupplierId());
		criteria.andPartIdEqualTo(incomingImportDto.getPartId());
		criteria.andMonthEqualTo(String.valueOf(month));
		List<Incoming> incomingbeanList = incomingDAO.selectIncomingByExample(example);
		// 修改
		if (incomingbeanList != null && incomingbeanList.size() != 0) {
			incomingBean = incomingbeanList.get(0);
			incomingBean.setAmount(incomingImportDto.getAmount());
			incomingDAO.updateIncomingByPrimaryKey(incomingBean);
		} else{
			Incoming incoming=new Incoming();
			org.springframework.beans.BeanUtils.copyProperties(incomingImportDto, incoming);
			List<Supplier> supplierList=supplierService.findSupplierByCode(incomingImportDto.getSupplierCode());
			if(supplierList!=null&&supplierList.size()>0){
				incoming.setSupplierId(supplierList.get(0).getId());
				incoming.setSupplierName(supplierList.get(0).getName());
			}
			List<Part> partList=partService.findPartByCode(incomingImportDto.getPartCode());
			if(partList!=null&&partList.size()>0){
				incoming.setPartId(partList.get(0).getId());
				incoming.setPartName(partList.get(0).getName());
			}
			incoming.setState(ConstantSqm.STATUS_NORMAL);
			incoming.setMonth(StringUtil.fixup(month));
			incoming.setYear(incomingImportDto.getYearStr());
			incomingDAO.insertIncoming(incoming);
		}
	}

    @Override
    public List<Incoming> getIncomingList(String year, String month) {
        IncomingExample example = new IncomingExample();
        IncomingExample.Criteria criteria = example.createCriteria();
        criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
        if(StringUtils.isEmpty(year) || StringUtils.isEmpty(month)){
            throw new SystemException(ConstantSqm.DATA_ERROR);
        }
        criteria.andYearEqualTo(year);
        criteria.andMonthLessThanOrEqualTo(month);
        return incomingDAO.selectIncomingByExample(example);

    }

    @Override
    public int findIncomingTotalByYearAndMonth(String year, String month) {
        if(StringUtils.isEmpty(year) || StringUtils.isEmpty(month)){
            throw new SystemException(ConstantSqm.DATA_ERROR);
        }
        IncomingExample example = new IncomingExample();
        IncomingExample.Criteria criteria = example.createCriteria();
        criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
        criteria.andYearEqualTo(year);
        criteria.andMonthEqualTo(month);
        List<Incoming> incomingList = incomingDAO.selectIncomingByExample(example);
        int total=0;
        for(Incoming incoming:incomingList){
            total=total+incoming.getAmount();
        }
        return total;
    }
}
